<template>
  <view class="edit-supplier">
    <!-- 表单内容 -->
    <scroll-view class="form-container" scroll-y>
      <form @submit="submitForm">
        <!-- 基础信息 -->
        <view class="form-section">
          <text class="section-title">基础信息</text>
          
          <view class="form-item">
            <text class="form-label required">供货商名称</text>
            <input 
              class="form-input" 
              v-model="formData.supplierName" 
              placeholder="请输入供货商名称"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">供货商类型</text>
            <picker 
              mode="selector" 
              :range="typeOptions" 
              :range-key="'label'"
              :value="typeIndex"
              @change="onTypeChange"
            >
              <view class="picker-value">
                {{ typeIndex >= 0 ? typeOptions[typeIndex].label : '请选择类型' }}
                <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">联系人</text>
            <input 
              class="form-input" 
              v-model="formData.contactPerson" 
              placeholder="请输入联系人姓名"
            />
          </view>

          <view class="form-item">
            <text class="form-label required">联系电话</text>
            <input 
              class="form-input" 
              v-model="formData.contactPhone" 
              type="number"
              placeholder="请输入11位手机号"
              maxlength="11"
            />
          </view>
          
          <view class="form-item" v-if="formData.supplierType === '0'">
            <text class="form-label">身份证号</text>
            <input 
              class="form-input" 
              v-model="formData.idCard" 
              placeholder="请输入身份证号"
              maxlength="18"
            />
          </view>
          
          <view class="form-item" v-if="formData.supplierType !== '0'">
            <text class="form-label">营业执照号</text>
            <input 
              class="form-input" 
              v-model="formData.businessLicense" 
              placeholder="请输入营业执照号"
            />
          </view>
        </view>

        <!-- 资质文件上传 -->
        <view class="form-section">
          <text class="section-title">资质文件</text>
          
          <view class="upload-area">
            <view v-if="!formData.qualificationFile" class="upload-placeholder" @click="uploadFile">
              <uni-icons type="camera" size="40" color="#999"></uni-icons>
              <text class="upload-text">点击上传资质文件</text>
            </view>
            <view v-else class="upload-preview">
              <image :src="getImageUrl(formData.qualificationFile)" mode="aspectFit" class="preview-image"></image>
              <view class="preview-actions">
                <button class="change-btn" @click="uploadFile">更换文件</button>
                <button class="remove-btn" @click="removeFile">删除文件</button>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 其他信息 -->
        <view class="form-section">
          <text class="section-title">其他信息</text>
          
          <view class="form-item">
            <text class="form-label">状态</text>
            <picker 
              mode="selector" 
              :range="statusOptions" 
              :range-key="'label'"
              :value="statusIndex"
              @change="onStatusChange"
            >
              <view class="picker-value">
                {{ statusIndex >= 0 ? statusOptions[statusIndex].label : '请选择状态' }}
                <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="form-textarea" 
              v-model="formData.remark" 
              placeholder="请输入备注信息"
              maxlength="200"
            />
          </view>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-actions">
          <button class="cancel-btn" @click="cancelEdit">取消</button>
          <button class="save-btn" form-type="submit">保存</button>
        </view>
      </form>
    </scroll-view>
  </view>
</template>

<script>
import { getSupplier, updateSupplier } from '@/api/system/supplier.js'
import upload from '@/utils/upload.js'
import config from '@/config'

export default {
  data() {
    return {
      supplierId: null,
      formData: {
        supplierName: '',
        supplierType: '0',
        contactPerson: '',
        contactPhone: '',
        idCard: '',
        businessLicense: '',
        qualificationFile: '',
        status: '0',
        remark: ''
      },
      typeOptions: [
        { value: '0', label: '个人' },
        { value: '1', label: '合作社' },
        { value: '2', label: '农贸市场' }
      ],
      statusOptions: [
        { value: '0', label: '正常' },
        { value: '1', label: '停用' }
      ],
      typeIndex: 0,
      statusIndex: 0
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.supplierId = options.id
      this.loadSupplierInfo()
    }
  },
  
  methods: {
    // 获取图片完整URL
    getImageUrl(path) {
      if (!path) return ''
      
      // 如果已经是完整URL或base64，直接返回
      if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('data:image')) {
        return path
      }
      
      // 如果是临时文件路径（上传前的本地预览）
      if (path.startsWith('blob:') || path.indexOf('tmp') > -1 || path.startsWith('wxfile://')) {
        return path
      }
      
      // 如果是相对路径，拼接baseUrl
      if (path.startsWith('/')) {
        return config.baseUrl + path
      }
      
      // 否则直接返回
      return path
    },
    
    // 加载供货商信息
    async loadSupplierInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await getSupplier(this.supplierId)
        
        if (response.code === 200 && response.data) {
          const data = response.data
          this.formData = {
            supplierName: data.supplierName || '',
            supplierType: data.supplierType || '0',
            contactPerson: data.contactPerson || '',
            contactPhone: data.contactPhone || '',
            idCard: data.idCard || '',
            businessLicense: data.businessLicense || '',
            qualificationFile: data.qualificationFile || '',
            status: data.status || '0',
            remark: data.remark || ''
          }
          
          // 设置选择器索引
          this.typeIndex = this.typeOptions.findIndex(item => item.value === this.formData.supplierType)
          this.statusIndex = this.statusOptions.findIndex(item => item.value === this.formData.status)
        } else {
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载供货商信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 类型选择变化
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.supplierType = this.typeOptions[this.typeIndex].value
    },
    
    // 状态选择变化
    onStatusChange(e) {
      this.statusIndex = e.detail.value
      this.formData.status = this.statusOptions[this.statusIndex].value
    },
    
    // 上传文件
    uploadFile() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 先显示本地图片
          this.formData.qualificationFile = tempFilePath
          
          // 上传图片到服务器
          uni.showLoading({ title: '上传中...' })
          
          upload({
            url: '/common/upload',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              storageType: 'local'
            }
          }).then(response => {
            uni.hideLoading()
            if (response && response.code === 200) {
              // 直接使用服务器返回的路径，不需要拼接
              // 因为后端会返回相对路径，前端显示时会自动处理
              this.formData.qualificationFile = response.url || response.fileName
              uni.showToast({
                title: '文件上传成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: response?.msg || '上传失败',
                icon: 'none'
              })
              // 上传失败，恢复原值
              this.loadSupplierInfo()
            }
          }).catch(error => {
            uni.hideLoading()
            console.error('上传失败:', error)
            uni.showToast({
              title: typeof error === 'string' ? error : '网络错误',
              icon: 'none'
            })
            // 上传失败，恢复原值
            this.loadSupplierInfo()
          })
        }
      })
    },
    
    // 删除文件
    removeFile() {
      this.formData.qualificationFile = ''
    },
    
    // 验证表单
    validateForm() {
      if (!this.formData.supplierName) {
        uni.showToast({
          title: '请输入供货商名称',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.contactPhone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        })
        return false
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.formData.contactPhone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.idCard && !/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(this.formData.idCard)) {
        uni.showToast({
          title: '身份证号格式不正确',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) return
      
      uni.showLoading({ title: '保存中...' })
      
      try {
        const submitData = {
          supplierId: this.supplierId,
          ...this.formData
        }
        
        console.log('提交的供货商数据:', submitData)
        
        const response = await updateSupplier(submitData)
        
        console.log('更新供货商响应:', response)
        
        uni.hideLoading()
        
        if (response.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
          
          // 返回详情页面
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.msg || '修改失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('修改供货商失败:', error)
        
        uni.showToast({
          title: '修改失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 取消编辑
    cancelEdit() {
      uni.showModal({
        title: '提示',
        content: '确定要取消编辑吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.edit-supplier {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding-bottom: 120rpx;
}

/* 表单区块 */
.form-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 30rpx;
  display: block;
}

/* 表单项 */
.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.form-label.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 8rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #333;
}

.form-textarea {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #333;
}

.picker-value {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 30rpx;
  color: #333;
}

/* 文件上传 */
.upload-area {
  border: 2rpx dashed #d9d9d9;
  border-radius: 16rpx;
  min-height: 300rpx;
  overflow: hidden;
  background-color: #fafafa;
}

.upload-placeholder {
  min-height: 300rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.upload-preview {
  position: relative;
}

.preview-image {
  width: 100%;
  height: 300rpx;
}

.preview-actions {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.95);
}

.change-btn,
.remove-btn {
  flex: 1;
  height: 70rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}

.change-btn {
  background: #1890ff;
  color: #fff;
}

.remove-btn {
  background: #fff;
  color: #ff4d4f;
  border: 2rpx solid #ff4d4f;
}

/* 底部按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx 40rpx;
  display: flex;
  gap: 30rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.cancel-btn,
.save-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.save-btn {
  background-color: #1890ff;
  color: #fff;
}
</style>